﻿/*
 * skills.js
 *
 * jQuery plugin to enahnce the layout and display of the skills list.
 */
(function ($) {
    var settings = {
        updateSkillUrl: '',
        skillUpdatedCallback: null,
        refreshSkillsUrl: '',
        skillsContainer: '',
        skillsCallback: null
    };

    var methods = {
        init: function (options) {
            settings = $.extend(settings, options);

            bindSkills();
        },
        refreshSkills: function () {
            _refreshSkills();
        },
        updateSkill: function (skillid, ranks) {
            //$(settings.skillsContainer).waiter();
            var url = settings.updateSkillUrl + '?skillid=' + skillid + '&ranks=' + ranks;

            //            doAjaxJsonGet(url,
            //                function (data) {
            //                    if (settings.skillUpdatedCallback)
            //                        settings.skillUpdatedCallback();

            //                    // show changes in skill list.
            //                    _refreshSkills(data);
            //                },
            //                showWarning
            //            );

            doAjaxGet(url,
                settings.skillsContainer,
                function () {
                    if (settings.skillUpdatedCallback)
                        settings.skillUpdatedCallback();

                    bindSkills(); // ensure these events are re bound to new html elements.

                    showMessage('Skill updated.');
                    // show changes in skill list.
                    //                    _refreshSkills(
                    //                        null,
                    //                        function () {
                    //                            $(settings.skillsContainer).waiter('destroy');
                    //                        });
                },
                function (data) {
                    showWarning(data);
                    //                    $(settings.skillsContainer).waiter('destroy');
                },
                false
            );
        }
    };

    $.fn.skills = function (method) {

        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on skills object.');
        }

    };

    // Bind the skills list event handlers.
    function bindSkills() {
        $('tr.skill-group').each(function () {
            var $header = $(this);

            $header.find('td').append('<a href="#" class="opener open">-</a>');
            $header.find('.opener').click(function (event) {
                event.preventDefault();

                var parentRow = $(this).parents('tr')[0];
                var group = $(parentRow).attr('group');

                if (!group)
                    return;

                var state = $(this).hasClass('open') ? 'open' : 'closed';

                if (state == 'open') { // close following siblings with matching group attribute.
                    $(parentRow).nextAll('tr[group=' + group + ']').hide();
                    $(this).removeClass('open').addClass('closed').html('+');
                }
                else {
                    $(parentRow).nextAll('tr[group=' + group + ']').fadeIn(400);
                    $(this).removeClass('closed').addClass('open').html('-');

                }
            });
        });
    }

    // Refresh the skills list from the json data of changes.
    function _refreshSkills(data, callback) {

        if (!data) {
            doAjaxGet(settings.refreshSkillsUrl, settings.skillsContainer,
                function () {
                    if (settings.skillsCallback)
                        settings.skillsCallback();

                    bindSkills(); // ensure these events are re bound to new html elements.

                    if (callback)
                        callback();
                },
                showMessage,
                true
            );
            return;
        }

        for (var i = 0; i < data.Data.length; i++) {
            var change = data.Data[i];

            // handle a new insertion.
            if (change.Added) {
                // find row header for this type.
                var $groupHeader = $(settings.skillsContainer).find('tr.skill-group[group=' + change.Item.Group + ']');

                if ($groupHeader) {
                    var $row = $('<tr group="' + change.Item.Group + '" skillid="' + change.Item.Slug + '"></tr>');

                    var maxRanks = (change.Item.MaxRanks > 0) ? change.Item.maxRanks : '-1';
                    var statusFlag = (change.Item.StatusSkill) ? 'S' : '';

                    $row.append('<td>' + change.Item.Name + '</td>');
                    $row.append('<td>' + change.Item.CostDescription + '</td>');
                    $row.append('<td><span class="editable" skillid="' + change.Item.Slug +
                        '" maxranks="' + maxRanks + '">' + change.Item.Ranks +
                        '</span> : <span class="points">' + change.Item.Cost + '</span></td>');
                    $row.append('<td>' + statusFlag + '</td>');

                    $groupHeader.after($row);
                }

                continue;
            }

            // find skill row.
            var $skillRow = $(settings.skillsContainer).find('tr[skillid=' + change.Item.Slug + ']');

            if (!$skillRow)
                continue;

            if (change.Removed) {
                $skillRow.fadeOut(300);
            }
            else if (change.Updated) {
                // update ranks.
                $skillRow.find('span.editable-text').html(change.Item.Ranks);

                // update cost.
                $skillRow.find('span.points').html(change.Item.Cost);

                // update maxranks.
                $skillRow.find('span.editable').attr('maxranks', change.Item.MaxRanks > 0 ? change.Item.MaxRanks : '-1');
            }
        }
    }

})(jQuery);